<script setup>
import { ref, onMounted } from 'vue'
import form_item from './components/form_item.vue';
import tip_text from './components/tip_text.vue'
import loadingBtn from '@/components/loadingBtn.vue'
import { ElMessage } from 'element-plus'
import { copys } from '@/utils/link/copy'
const loading = ref(false)
const nat = ref({
    stun: 'stun.qq.com',
    port: '3478'
})
const result = ref('')
function check() {
    return new Promise((resolve, reject) => {
        window.go.main.NatPage.NTP_Set_addr(nat.value.stun).then(msg => {
            if (msg !== 'ok') {
                ElMessage.info("设置ip失败")
                resolve()
            }
        })
        window.go.main.NatPage.NTP_Set_port(nat.value.port).then(res => {
            if (res !== 'ok') {
                ElMessage.info("设置端口失败")
                resolve()
            }
        })

        window.go.main.NatPage.NTP_checking()
        window.runtime.EventsOnMultiple('nat', (msg) => {
            result.value = msg
            resolve()
        }, 1)
    })
}

function copy() {
    if (result.value == '' || result.value.indexOf("外网IP") == -1) {
        ElMessage.info("未检测到外网ip")
        return
    }
    let arr = result.value.split("外网IP: ")
    copys(arr[1])
    ElMessage.success("已为您复制外网IP到剪贴板")

}
</script>

<template>
    <div class="back">
        <div class="test">
            <form_item v-model="nat.stun" label="STUN服务器"></form_item>
            <form_item v-model="nat.port" label="端口"></form_item>
            <div class="btn">
                <loadingBtn :function="check" class="checkBtn">开始检测</loadingBtn>
                <!-- <el-button @click="check" class="checkBtn" v-loading="loading" element-loading-text="检测中"
                    type="primary">开始检测</el-button> -->
            </div>
        </div>
        <div class="result" v-if="result !== ''">
            <div v-if="result.indexOf('外网IP: ') !== -1">
                <span>监测成功!</span>
                <span class="copybtn">{{ result }}</span>
                <el-button class="copybtn" @click="copy">
                    <el-icon>
                        <CopyDocument />
                    </el-icon>
                </el-button>
            </div>
            <div v-else>{{ result }} </div>
        </div>
        <tip_text />
    </div>
</template>

<style scoped lang="less">
.copybtn {
    margin-left: 20px;
}

.result {
    margin: 20px 10px 20px 10px;
}

.test {
    width: 500px;
}

.checkBtn {
    width: 95%;
}

.btn {
    text-align: right;
    margin-top: 10px;
}
</style>